<?php
namespace app\bsadmin\controller;
use app\common\UploadFile;
class Ueditor extends Base
{
    /**
     * [__construct 构造函数]
     * @return [type] [description]
     */
    public function __construct(){
        header('Access-Control-Allow-Origin: *'); //设置http://www.baidu.com允许跨域访问
        header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); //设置允许的跨域header
    }
    public function getConfig()
    {
        $action=$_GET['action'];
        $this->CONFIG=config('ueditor.config');
        $result;
        switch ($action) {
            case 'config':
                $result=json_encode($this->CONFIG);
                break;
            /* 上传图片 */
            case 'uploadimage':
                $result = $this->uploadUeditorImage();
                break;
            /* 上传涂鸦 */
            case 'uploadscrawl':
                $result = json_encode([
                    'state'=> '请求地址出错'
                ]);
                // $result = $this->uploadUeditorScrawl();
                break;
            /* 上传视频 */
            case 'uploadvideo':
                $result = $this->uploadUeditorVideo();
                break;
            /* 上传文件 */
            case 'uploadfile':
                $result = $this->uploadUeditorFile();
                break;

            /* 列出图片 */
            case 'listimage':
                $result=$this->getListImg();
                break;
            /* 列出文件 */
            case 'listfile':
                $result=$this->getListFile();
                break;

            /* 抓取远程文件 */
            case 'catchimage':
                $D=request()->post();
                $Data=['state'=>'SUCCESS'];
                foreach ($D['source'] as $k => $v) {
                    $result=$this->downloadUeditorImage($v);
                    if ($result['state']=='SUCCESS') {
                        $Data['list'][$k]=$result;
                    }else{
                        $Data['list'][$k]=$result;
                    }
                    $Data['list'][$k]['source']=$v;
                }
                $result = json_encode($Data);
                break;
            default:
                $result = json_encode([
                    'state'=> '请求地址出错'
                ]);
                break;
        }
        /* 输出结果 */
        if (isset($_GET["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
                die;
            } else {
                echo json_encode([
                    'state'=> 'callback参数不合法'
                ]);
                die;
            }
        } else {
            echo $result;
			die;
        }
    }
    public function getListFile()
    {
        $allowFiles = $this->CONFIG['fileManagerAllowFiles'];
        $listSize = $this->CONFIG['fileManagerListSize'];
        $path = $this->CONFIG['fileManagerListPath'];
        $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);

        /* 获取参数 */
        $size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
        $start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
        $end = $start + $size;

        /* 获取文件列表 */
        $path = root_path().'public/uploads/'.$path;
        $files = $this->getfiles($path, $allowFiles);
        if (!count($files)) {
            return json_encode([
                "state" => "no match file",
                "list" => [],
                "start" => $start,
                "total" => count($files)
            ]);
        }

        /* 获取指定范围的列表 */
        $len = count($files);
        for ($i = min($end, $len) - 1, $list = []; $i < $len && $i >= 0 && $i >= $start; $i--){
            $list[] = $files[$i];
        }
        //倒序
        //for ($i = $end, $list = []; $i < $len && $i < $end; $i++){
        //    $list[] = $files[$i];
        //}

        /* 返回数据 */
        $result = json_encode([
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => count($files)
        ]);

        return $result;
    }

    /**
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param array $files
     * @return array
     */
    function getfiles($path, $allowFiles, &$files = [])
    {
        if (!is_dir($path)) return $files;
        if(substr($path, strlen($path) - 1) != '/') $path .= '/';
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                if (is_dir($path2)) {
                    $this->getfiles($path2, $allowFiles, $files);
                } else {
                    if (preg_match("/\.(".$allowFiles.")$/i", $file)) {
                        $files[] = [
                            'url'=> config('web.imgurl').'/'.str_replace('/www/wwwroot/www.lzsf.com/public/','',$path2),
                            'mtime'=> filemtime($path2)
                        ];
                    }
                }
            }
        }
        return $files;
    }
    public function getListImg()
    {
        $allowFiles = $this->CONFIG['imageManagerAllowFiles'];
        $listSize = $this->CONFIG['imageManagerListSize'];
        $path = $this->CONFIG['imageManagerListPath'];
        $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);

        /* 获取参数 */
        $size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
        $start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
        $end = $start + $size;

        /* 获取文件列表 */
        $path = root_path().'public/uploads/' . $path;
        $files = $this->getfiles($path, $allowFiles);
        if (!$files || !count($files)) {
            return json_encode([
                "state" => "no match file",
                "list" => [],
                "start" => $start,
                "total" => count($files)
            ]);
        }

        /* 获取指定范围的列表 */
        $len = count($files);
        for ($i = min($end, $len) - 1, $list = []; $i < $len && $i >= 0 && $i >= $start; $i--){
            $list[] = $files[$i];
        }
        //倒序
        //for ($i = $end, $list = []; $i < $len && $i < $end; $i++){
        //    $list[] = $files[$i];
        //}

        /* 返回数据 */
        $result = json_encode([
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => count($files)
        ]);

        return $result;
    }
    public function uploadUeditorVideo($value='')
    {
    	$ret=UploadFile::upload(0,$this->CONFIG['videoFieldName']);
    	if ($ret['code'] == 0) {
            return json_encode([
                "state" => 'SUCCESS',
                "url" => $ret['data']['url'],
                "title" => date('YmdHis'),
                "original" => $ret['data']['name'],
                "type" => $ret['data']['file_type'],
                "size" => $ret['data']['file_size']
            ]);
    	}else{
            return json_encode([
                "state" => $ret['msg'],
            ]);
    	}
    }
    public function uploadUeditorFile()
    {
    	$ret=UploadFile::upload(0,$this->CONFIG['fileFieldName']);
    	if ($ret['code'] == 0) {
            return json_encode([
                "state" => 'SUCCESS',
                "url" => $ret['data']['url'],
                "title" => date('YmdHis'),
                "original" => $ret['data']['name'],
                "type" => $ret['data']['file_type'],
                "size" => $ret['data']['file_size']
            ]);
    	}else{
            return json_encode([
                "state" => $ret['msg'],
            ]);
    	}
    }
    public function uploadUeditorImage()
    {
    	$ret=UploadFile::upload(0,$this->CONFIG['imageFieldName']);
    	if ($ret['code'] == 0) {
            return json_encode([
                "state" => 'SUCCESS',
                "url" => $ret['data']['url'],
                "title" => date('YmdHis'),
                "original" => $ret['data']['name'],
                "type" => $ret['data']['file_type'],
                "size" => $ret['data']['file_size']
            ]);
    	}else{
            return json_encode([
                "state" => $ret['msg'],
            ]);
    	}
    }
    public function downloadUeditorImage($url)
    {
        $ret=UploadFile::downImage($this->CONFIG['imageFieldName'],$url);
        if ($ret['code'] == 0) {
            return [
                "state" => 'SUCCESS',
                "url" => $ret['data']['url'],
                "title" => date('YmdHis'),
                "original" => 'remote.png',
                "type" => $ret['data']['file_type'],
                "size" => $ret['data']['file_size']
            ];
        }else{
            return [
                "state" => $ret['msg'],
            ];
        }
    }
}
